package com.dong.cutesms.utils;

import java.util.ArrayList;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.ContactsContract.PhoneLookup;
import android.provider.ContactsContract;

import com.dong.cutesms.constant.AppConstant;
import com.dong.cutesms.constant.SmsTable;
import com.dong.cutesms.models.Config;
import com.dong.cutesms.models.DBHelper_DB;
import com.dong.cutesms.models.PeopleModel;
import com.dong.cutesms.models.Sms;
import com.dong.cutesms.models.SmsModel;

public class SmsUtils {
	ContentResolver contentResolver;
	ArrayList<String> phoneNumList;
	ArrayList<Integer> threadIDList;
	ArrayList<PeopleModel> listPeople;
	DBHelper_DB dbheper_db;
	Context context;

	public SmsUtils(ContentResolver _contentResolver, Context _context) {
		contentResolver = _contentResolver;
		context = _context;
		dbheper_db = new DBHelper_DB(context);
	}

	public void importSms() {
		phoneNumList = new ArrayList<String>();
		threadIDList = new ArrayList<Integer>();
		listPeople = new ArrayList<PeopleModel>();
		String[] projection = { SmsTable.ADDRESS, SmsTable.THREAD_ID,
				SmsTable.DATE, SmsTable.BODY };
		Cursor cursor = contentResolver.query(Uri.parse("content://sms/"),
				projection, null, null, null);
		int indexAddr = cursor.getColumnIndex(SmsTable.ADDRESS);
		int indexThreadID = cursor.getColumnIndex(SmsTable.THREAD_ID);
		int indexDate = cursor.getColumnIndex(SmsTable.DATE);
		int indexBody = cursor.getColumnIndex(SmsTable.BODY);

		if (indexAddr < 0 || !cursor.moveToFirst())
			return;

		do {
			String address = cursor.getString(indexAddr);
			if (address != null) {
				int threadID = cursor.getInt(indexThreadID);
				long date = cursor.getLong(indexDate);
				String body = cursor.getString(indexBody);
				add2PhoneNumList(address, threadID, date, body);
			}
		} while (cursor.moveToNext());

		for (int i = 0; i < listPeople.size(); i++) {
			String displayName = getContactDisplayNameByNumber(listPeople
					.get(i).phoneNumber);
			if (displayName.equals("?")) {
				displayName = listPeople.get(i).phoneNumber;
			}
			listPeople.get(i).displayName = displayName.trim();
			dbheper_db.addPeople(listPeople.get(i));

		}
		
		//set User Information
		Config config = new Config(AppConstant.USER_AVATAR, String.valueOf(AppConstant.listAvatar[3]));
		dbheper_db.addConfig(config);

	}

	public int getStatusAccess() {
		Config config = dbheper_db.getConfig(AppConstant.STATUS_ACCESS);
		if (config == null) {
			return 0;
		}
		return 1;
	}

	public void addConfig(Config config) {
		dbheper_db.addConfig(config);
	}

	public ArrayList<PeopleModel> getPeopleList() {
		return dbheper_db.getPeople();
	}

	private void add2PhoneNumList(String address, int threadID, long date,
			String body) {

		if (listPeople.size() == 0) {

			listPeople.add(new PeopleModel(threadID, address.trim(), body.trim(), date));
		} else {
			boolean exist = false;
			for (int i = 0; i < listPeople.size(); i++) {
				int iThreadID = listPeople.get(i).threadID;
				if (threadID == iThreadID) {
					exist = true;
					break;
				}
			}
			if (exist == false) {
				listPeople.add(new PeopleModel(threadID, address.trim(), body.trim(), date));
			}
		}
	}

	public ArrayList<SmsModel> getSmsList(PeopleModel people) {
		ArrayList<SmsModel> smsList = new ArrayList<SmsModel>();
		String[] projection = { SmsTable.BODY, SmsTable.ADDRESS,
				SmsTable.STATUS, SmsTable._ID, SmsTable.TYPE };
		String selection = SmsTable.THREAD_ID + "='" + people.threadID + "'";
		Cursor cursor = contentResolver.query(Uri.parse("content://sms/"),
				projection, selection, null, null);

		int indexBody = cursor.getColumnIndex(SmsTable.BODY);
		int indexStatus = cursor.getColumnIndex(SmsTable.STATUS);
		int indexID = cursor.getColumnIndex(SmsTable._ID);
		int indexType = cursor.getColumnIndex(SmsTable.TYPE);
		if (indexBody < 0 || !cursor.moveToFirst())
			return null;

		smsList.clear();
		int i = 0;
		do {
			String body = cursor.getString(indexBody);
			int id = cursor.getInt(indexID);
			int type = cursor.getInt(indexType);
			int status = cursor.getInt(indexStatus);
			if (status != 0) {
				SmsModel sms = new SmsModel(people.phoneNumber,
						people.displayName, body, id, type);
				smsList.add(sms);

			}
			i++;

			// System.out.println("sms status:" + String.valueOf(status));
			// System.out.println("sms id:" + String.valueOf(id));

		} while (cursor.moveToNext());
		return smsList;
	}
	
	public ArrayList<SmsModel> getSmsListReverse(PeopleModel people) {
		ArrayList<SmsModel> smsList = new ArrayList<SmsModel>();
		String[] projection = { SmsTable.BODY, SmsTable.ADDRESS,
				SmsTable.STATUS, SmsTable._ID, SmsTable.TYPE };
		String selection = SmsTable.THREAD_ID + "='" + people.threadID + "'";
		Cursor cursor = contentResolver.query(Uri.parse("content://sms/"),
				projection, selection, null, null);

		int indexBody = cursor.getColumnIndex(SmsTable.BODY);
		int indexStatus = cursor.getColumnIndex(SmsTable.STATUS);
		int indexID = cursor.getColumnIndex(SmsTable._ID);
		int indexType = cursor.getColumnIndex(SmsTable.TYPE);
		if (indexBody < 0 || !cursor.moveToFirst())
			return null;

		smsList.clear();
		int i = 0;
		do {
			String body = cursor.getString(indexBody);
			int id = cursor.getInt(indexID);
			int type = cursor.getInt(indexType);
			int status = cursor.getInt(indexStatus);
			if (status != 0) {
				SmsModel sms = new SmsModel(people.phoneNumber,
						people.displayName, body, id, type);
				smsList.add(0,sms);

			}
			i++;

			// System.out.println("sms status:" + String.valueOf(status));
			// System.out.println("sms id:" + String.valueOf(id));

		} while (cursor.moveToNext());
		return smsList;
	}

	public String getContactDisplayNameByNumber(String number) {
		Uri uri = Uri.withAppendedPath(
				ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
				Uri.encode(number));
		String name = "?";

		Cursor contactLookup = contentResolver.query(uri, new String[] {
				BaseColumns._ID, ContactsContract.PhoneLookup.DISPLAY_NAME },
				null, null, null);

		try {
			if (contactLookup != null && contactLookup.getCount() > 0) {
				contactLookup.moveToNext();
				name = contactLookup.getString(contactLookup
						.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
				// String contactId =
				// contactLookup.getString(contactLookup.getColumnIndex(BaseColumns._ID));
			}
		} finally {
			if (contactLookup != null) {
				contactLookup.close();
			}
		}

		return name;
	}

	public void deleteSMS(int id) {
		ContentValues values = new ContentValues();
		values.put("status", 0);
		String where = "_id='" + id + "'";
		int result = contentResolver.update(Uri.parse("content://sms/"),
				values, where, null);
	}

	public void getTableContent(Cursor cursor) {
		StringBuffer info = new StringBuffer();
		for (int i = 0; i < cursor.getColumnCount(); i++) {
			info.append("Column: " + cursor.getColumnName(i) + "\n");
		}

		if (!cursor.moveToFirst())
			return;

		do {
			for (int i = 0; i < cursor.getColumnCount(); i++) {
				System.out.print(cursor.getString(i) + "    ");
			}
			System.out.println();
		} while (cursor.moveToNext());
	}

	public void getTableColumn(Cursor cursor) {
		StringBuffer info = new StringBuffer();
		for (int i = 0; i < cursor.getColumnCount(); i++) {
			info.append("Column: " + cursor.getColumnName(i) + "\n");
		}

		System.out.println(info.toString());
	}

	public void showTable() {
		Cursor cusor = contentResolver.query(Uri.parse("content://sms/"), null,
				null, null, null);
		getTableContent(cusor);
	}

	public void UnDeleteAllSMS() {
		ContentValues values = new ContentValues();
		values.put("status", -1);
		int result = contentResolver.update(Uri.parse("content://sms/"),
				values, null, null);
	}

	public int getThreadIdByPhoneNumber(String phoneNumber) {
		String[] projection = { SmsTable.THREAD_ID };
		String args[] = { phoneNumber };
		Cursor cursor = contentResolver.query(Uri.parse("content://sms/"),
				projection, SmsTable.ADDRESS + "=?", args, null);

		if (!cursor.moveToFirst()) {
			return -1;
		}

		return cursor.getInt(cursor.getColumnIndex(SmsTable.THREAD_ID));
	}
	
	public int getIDRecentSentSms(Uri uri){
		Cursor cursor = contentResolver.query(uri, null, null, null, null);
		if(!cursor.moveToFirst())
			return -1;
		
		return cursor.getInt(cursor.getColumnIndex(SmsTable._ID));
	}

	public Uri push2SmsTable(Sms sms) {
		ContentValues values = new ContentValues();
		values.put(SmsTable.THREAD_ID, sms.THREAD_ID);
		values.put(SmsTable.ADDRESS, sms.ADDRESS);
		values.put(SmsTable.PERSON, sms.PERSON);
		values.put(SmsTable.DATE, sms.DATE);
		values.put(SmsTable.PROTOCOL, sms.PROTOCOL);
		values.put(SmsTable.READ, sms.READ);
		values.put(SmsTable.STATUS, sms.STATUS);
		values.put(SmsTable.TYPE, sms.TYPE);
		values.put(SmsTable.REPLY_PATH_PRESENT, sms.REPLY_PATH_PRESENT);
		values.put(SmsTable.SUBJECT, sms.SUBJECT);
		values.put(SmsTable.BODY, sms.BODY);
		values.put(SmsTable.SERVICE_CENTER, sms.SERVICE_CENTER);
		values.put(SmsTable.LOCKED, sms.LOCKED);
		values.put(SmsTable.ERROR_CODE, sms.ERROR_CODE);
		values.put(SmsTable.SEEN, sms.SEEN);
		values.put(SmsTable.DELETABLE, sms.DELETABLE);
		values.put(SmsTable.DELIVERY_DATE, sms.DELIVERY_DATE);

		return contentResolver.insert(Uri.parse("content://sms/"), values);
	}

	public void showPeopleTable() { // contact
		Cursor cursor = contentResolver.query(
				ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		getTableContent(cursor);
	}

	public void showPeopleTableColumn() {
		Cursor cursor = contentResolver.query(
				ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		getTableColumn(cursor);
	}

	public void getPeopleIDByPhoneNumber(String phoneNumber) {
		String projection[] = { PhoneLookup.DISPLAY_NAME,
				PhoneLookup.HAS_PHONE_NUMBER, PhoneLookup._ID };
		Cursor cursor = contentResolver.query(
				ContactsContract.Contacts.CONTENT_URI, projection, null, null,
				null);
		if (!cursor.moveToFirst()) {
			return;
		}
		int indexID = cursor.getColumnIndex(PhoneLookup._ID);
		int indexDisplayName = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME);
		int indexNumber = cursor.getColumnIndex(PhoneLookup.HAS_PHONE_NUMBER);
		do {
			int id = cursor.getInt(indexID);
			String displayName = cursor.getString(indexDisplayName);
			String number = cursor.getString(indexNumber);

			System.out.println(String.valueOf(id) + "   " + displayName + "   "
					+ number);
		} while (cursor.moveToNext());
	}

	public int getContactIDByNameAndPhoneNumber(String displayName,
			String phoneNumber) {
		String projection[] = { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID };
		String args[] = { displayName};
		Cursor cursor = contentResolver.query(
				ContactsContract.Contacts.CONTENT_URI, projection,
				PhoneLookup.DISPLAY_NAME + "=?", args, null);
		
		if(cursor.getCount()==0){
			return -1;
		}
		if(cursor.getCount()==1){
			cursor.moveToFirst();
			int contactID = cursor.getInt(cursor.getColumnIndex(PhoneLookup._ID));
			return contactID;
		}else{
			
		}
		
		return -1;
	}
	
	public int getDisplayNameByPhoneNumber(String phoneNumber) {
		String projection[] = { PhoneLookup.DISPLAY_NAME };
		String args[] = { phoneNumber};
		Cursor cursor = contentResolver.query(
				ContactsContract.Contacts.CONTENT_URI, projection,
				PhoneLookup.DISPLAY_NAME + "=?", args, null);
		
		if(cursor.getCount()==0){
			return -1;
		}
		if(cursor.getCount()==1){
			cursor.moveToFirst();
			int contactID = cursor.getInt(cursor.getColumnIndex(PhoneLookup._ID));
			return contactID;
		}else{
			
		}
		
		return -1;
	}
	
	public String getDisplayNameByContactID(int contactID){
		String projection[] = { PhoneLookup.DISPLAY_NAME };
		String args[] = { String.valueOf(contactID)};
		Cursor cursor = contentResolver.query(
				ContactsContract.Contacts.CONTENT_URI, projection,
				PhoneLookup._ID + "=?", args, null);
		
		if(!cursor.moveToFirst()){
			return null;
		}
		return cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
	}
	public PeopleModel getPeopleByThreadID(int threadID) {
		return dbheper_db.getPeopleByThreadID(threadID);
	}

	public void addPeople(PeopleModel people) {
		dbheper_db.addPeople(people);
	}

	public void updatePeople(PeopleModel people) {
		dbheper_db.updatePeople(people);
	}

	public void removePeople(int threadID) {
		dbheper_db.removePeople(threadID);
	}
	
	public void changeAvatar(PeopleModel people, int avatarID){
		people.avatarID = avatarID;
		dbheper_db.updatePeople(people);
	}
	
	public int getUserAvatar(){
		System.out.println(dbheper_db.getConfig(AppConstant.USER_AVATAR).value);
		return Integer.parseInt(dbheper_db.getConfig(AppConstant.USER_AVATAR).value);
	}
}
